package bpm.dao.impl.user;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import bpm.dao.user.OrgTrResourceDao;
import bpm.domain.user.OrgTrResource;
/**
 * 
 * @author ZhaoWangLong Jul 15, 2011
 *
 */
@Repository("orgTrResourceDao")
public class OrgTrResourceDaoImpl implements OrgTrResourceDao {
	@Resource
	private JdbcTemplate jdbcTemplate;
	private Logger logger=Logger.getLogger(OrgTrResourceDaoImpl.class);
	@SuppressWarnings("unchecked")
	public List<OrgTrResource> findResourceByRole(String roleId) {
		String sql="select MAIN_ID, MODULE_ID, RESOURCE_NAME, URL, RESOURCE_REMARK from ORG_TR_RESOURCE "+
			" where MAIN_ID in (select RESOURCE_ID from ORG_TR_GROUPRESOURCE where GROUP_ID=?)";
		logger.debug("QuerySQL:"+sql);
		return this.jdbcTemplate.query(sql, new Object[]{roleId},new OrgTrResourceRowMapper());
	}
	@SuppressWarnings("unchecked")
	public List<OrgTrResource> findResourceByUser(String userId) {
		String sql="select MAIN_ID, MODULE_ID, RESOURCE_NAME, URL, RESOURCE_REMARK from ORG_TR_RESOURCE " +
			"  where MAIN_ID in (select RESOURCE_ID from ORG_TR_GROUPRESOURCE where GROUP_ID in ( "+
			"  select GROUPID from ORG_GROUPUSER where userid =? ))";
		logger.debug("QuerySQL:"+sql);
		return this.jdbcTemplate.query(sql, new Object[]{userId},new OrgTrResourceRowMapper());
	}
	public void update(String roleId, String[] resourceIds) {
		String delete="delete from ORG_TR_GROUPRESOURCE where group_id=?";
		logger.debug("DeleteSQL:"+delete);
		this.jdbcTemplate.update(delete,new Object[]{roleId});
		if(resourceIds!=null&&resourceIds.length>0){
			StringBuffer insert =new StringBuffer();
			insert.append("insert into ORG_TR_GROUPRESOURCE(MAIN_ID, GROUP_ID, RESOURCE_ID) values ");
			for (int i = 0; i < resourceIds.length; i++) {
				if(i!=resourceIds.length-1){
					insert.append("('").append(roleId+"_"+resourceIds[i]).append("','")
						  .append(roleId).append("','")
						  .append(resourceIds[i]).append("'), ");
				}else{
					insert.append("('").append(roleId+"_"+resourceIds[i]).append("','")
					  .append(roleId).append("','")
					  .append(resourceIds[i]).append("') ");
				}
			}	
			logger.debug("InsertSQL:"+insert.toString());
			this.jdbcTemplate.update(insert.toString());
		}
	}
	@SuppressWarnings("unchecked")
	public List<OrgTrResource> findAllResource() {
		String sql="select MAIN_ID, MODULE_ID, RESOURCE_NAME, URL, RESOURCE_REMARK from ORG_TR_RESOURCE";
		logger.debug("QuerySQL:"+sql);
		return this.jdbcTemplate.query(sql,new OrgTrResourceRowMapper());
	}
}
